package com.owen.cyclic.barrier.simple2;

import java.sql.Time;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class MyRunnable2 implements Runnable {

    private CyclicBarrier cyclicBarrier;
    private String name;
    private int sleep;

    public MyRunnable2(CyclicBarrier cyclicBarrier,String name,int sleep){
        this.cyclicBarrier=cyclicBarrier;
        this.name=name;
        this.sleep=sleep;
    }

    public void eat(){
        try {
            TimeUnit.SECONDS.sleep(sleep);
            long startTime=System.currentTimeMillis();
            cyclicBarrier.await();
            long endTime=System.currentTimeMillis();
            System.out.println(name+", sleep: "+sleep+" 等待了"+(endTime-startTime)+"(ms)，开始吃饭了！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }

    public void drive(){
        try {
            TimeUnit.SECONDS.sleep(sleep);
            long startTime=System.currentTimeMillis();
            cyclicBarrier.await();
            long endTime=System.currentTimeMillis();
            System.out.println(name+", sleep: "+sleep+" 等待了"+(endTime-startTime)+"(ms)，去下一景点的路上！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        eat();

        drive();
    }
}
